package com.aliyun.oss.service.impl;

import com.aliyun.oss.mapper.FoodMapper;
import com.aliyun.oss.pojo.DTO.AddFoodDTO;
import com.aliyun.oss.pojo.Entity.Food;
import com.aliyun.oss.pojo.Entity.dishFlavor;
import com.aliyun.oss.pojo.Vo.FoodVO;
import com.aliyun.oss.pojo.Vo.GetFoodByIdVO;
import com.aliyun.oss.service.DishFlavorService;
import com.aliyun.oss.service.FoodService;
import com.aliyun.oss.utils.AliyunOssOperator;
import com.aliyun.oss.utils.GetNowTime;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements FoodService {
    @Autowired
    FoodMapper foodMapper;
    @Autowired
    AliyunOssOperator AliyunOSSOperator;

    @Autowired
    DishFlavorService dishFlavorService;

    @Override
    public List<FoodVO> getAllFoods() {
        List<FoodVO> foodVOList = foodMapper.getAllFoods();
        return foodVOList;
    }

    @Override
    public List<FoodVO> queryFoodLikeByNameOrCategoryIdOrStatus(String name, Integer categoryId, Integer status) {
        List<FoodVO> foodVOList = foodMapper.queryFoodLikeByNameOrCategoryIdOrStatus(name, categoryId, status);
        return foodVOList;
    }

    @Override
    public void deleteFoodById(Integer id) {
//        根据id删除菜品
        removeById(id);

    }

    @Override
    public void updateFoodStatusById(Integer operateId, Integer id, Integer status) {
        LocalDateTime nowTime = GetNowTime.getNowTime();
        update(new UpdateWrapper<Food>().set("status",status).set("update_time",nowTime).set("update_user",id).eq("id",id));
    }

    @Override
    public void BatchDeleteFoodsByIds(String[] ids) {
//        根据数组中的id批量删除
        removeByIds(Arrays.asList(ids));

    }

    @Override
    public void addFood(Integer operateId, AddFoodDTO addFoodDTO) throws JsonProcessingException {
        LocalDateTime nowTime = GetNowTime.getNowTime();
        byte[] content = null;
        String originalFilename = null;
        String imageUrl = null;
        MultipartFile imageFile = addFoodDTO.getImageUrl();
        if (imageFile != null && !imageFile.isEmpty()) {
            try {
                content = imageFile.getBytes();
                originalFilename = imageFile.getOriginalFilename(); // 安全调用
                // 调用阿里云 OSS 上传图片
                imageUrl = AliyunOSSOperator.upload(content, originalFilename);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            imageUrl = null;
        }
//        将addFoodDTO中的数据分别插入Food和dish_flavor表中
        Food food = new Food(addFoodDTO.getName(),addFoodDTO.getCategoryId(),addFoodDTO.getPrice(),imageUrl,addFoodDTO.getDescription(),1,nowTime,nowTime,operateId,operateId);
        save(food);
//        获取插入后返回的新的id，// 插入数据，并将生成的ID回填到food对象中
        Integer id = food.getId();
//        数组转换为json格式存储
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonValue = objectMapper.writeValueAsString(addFoodDTO.getFlavorValue());
        dishFlavor dishFlavor = new dishFlavor(id, addFoodDTO.getFlavorName(), jsonValue);
        dishFlavorService.save(dishFlavor);

    }

    @Override
    public GetFoodByIdVO getFoodById(Integer operateId, Integer id) {
//        根据id查询数据
        Food food = getById(id);
        dishFlavor dishFlavor = dishFlavorService.getOne(new UpdateWrapper<dishFlavor>().eq("dish_id",id));
//        组合数据并返回
        if(dishFlavor== null){
            return new GetFoodByIdVO(food.getName(),food.getCategoryId(),food.getPrice(),food.getDescription(),food.getImage(),null,null);
        }else {
            return  new GetFoodByIdVO(food.getName(), food.getCategoryId(), food.getPrice(), food.getDescription(), food.getImage(), dishFlavor.getName(), dishFlavor.getValue());
        }
    }

    @Override
    public void updateFoodById(Integer operateId, AddFoodDTO addFoodDTO) throws JsonProcessingException, ClientException {
//        获取当前时间
        LocalDateTime nowTime = GetNowTime.getNowTime();
//        先获取旧图片地址，调用deleteByUrl删除，在先判断是否有图片，有则在删上传图片
        String oldImageUrl = getById(addFoodDTO.getId()).getImage();
        if (oldImageUrl != null) {
            AliyunOSSOperator.deleteByUrl(oldImageUrl);
        }
        byte[] content = null;
        String originalFilename = null;
        String imageUrl = null;
        MultipartFile imageFile = addFoodDTO.getImageUrl();
        if (imageFile != null && !imageFile.isEmpty()) {
            try {
                content = imageFile.getBytes();
                originalFilename = imageFile.getOriginalFilename();
                imageUrl = AliyunOSSOperator.upload(content, originalFilename);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        Food food = new Food(addFoodDTO.getId(),addFoodDTO.getName(),addFoodDTO.getCategoryId(),addFoodDTO.getPrice(),imageUrl,addFoodDTO.getDescription(),1,nowTime,operateId);
        updateById(food);
        //        数组转换为json格式存储
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonValue = objectMapper.writeValueAsString(addFoodDTO.getFlavorValue());
        dishFlavorService.update(new UpdateWrapper<dishFlavor>().set("name",addFoodDTO.getFlavorName()).set("value",jsonValue).eq("dish_id",addFoodDTO.getId()));

    }
}
